package com.lifp.thread.lock.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description 读写锁 示例
 * @Author lfp
 * @Date 2022/8/5
 * @Version 1.0
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        //资源类
        MyCache myCache = new MyCache();

        //创建线程放数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(()->{
                myCache.put(num + "",num + "");
            },String.valueOf(i)).start();
        }

        //创建线程读取数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(()->{
                myCache.get(num + "");
            },String.valueOf(i)).start();
        }
    }
}

//资源类
class MyCache {

    //1、创建Map集合
    private volatile Map<String,Object> map = new HashMap<>();


    //2、创建读写锁
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();


    //3、存数据
    public void put(String key, Object value){
        //3.1、添加写锁
        rwLock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + " 正在写："+key);

            //3.2、暂停一会儿
            TimeUnit.MILLISECONDS.sleep(300);

            //3.3、存入数据
            map.put(key,value);

            System.out.println(Thread.currentThread().getName() + " 写完了！："+key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //3.4、释放锁
            rwLock.writeLock().unlock();
        }

    }

    //4、取数据
    public Object get(String key){
        //4.1、添加读锁
        rwLock.readLock().lock();

        Object result = null;

        try {
             System.out.println(Thread.currentThread().getName() + " 正在读取："+key);

            //4.2、暂停一会儿
            TimeUnit.MILLISECONDS.sleep(300);

            //4.3、取数据
            Object value = result = map.get(key);

            System.out.println(Thread.currentThread().getName() + " 已经取完了=>"+key + ":" + value.toString());
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //4.4、释放锁
            rwLock.readLock().unlock();
        }
        return result;
    }
}